import nme.Assets;
import nme.display.Graphics;
import nme.display.Sprite;
import nme.display.Bitmap;
import nme.display.BitmapData;

import nme.geom.Rectangle;
import nme.geom.Matrix;
import nme.geom.Point;

class GameStateManager
{
	private var _queue:Array<IGameState>;
	private var _currentState:IGameState;
	private var _currentStateId:Int;
	private var _timer:haxe.Timer;
	private var _main:Sprite;
	private static var _manager:GameStateManager = new GameStateManager();
	
	private function new ()
	{
		_queue = new Array<IGameState> ();
		_timer = new haxe.Timer (1000/60);
		_timer.run = run;
	}
	
	private function run ():Void
	{
		if (_currentState == null)
		{
			if (_queue.length > 0)
			{
				_currentState = _queue.shift ();
				_main.addChild (cast(_currentState, Sprite));
			}
		}
		
		if (_currentState != null)
		switch (_currentState._substate)
		{
			case SubState.LOADING_STATE:
				if (_currentState.loadingCompleted())
					_currentState.init ();
				else
					_currentState.loading ();
			case SubState.LOOP_STATE:
				_currentState.loop ();
			case SubState.DESTROY_STATE:
				_currentState.destroy ();
				_main.removeChild (cast(_currentState, Sprite));
				_currentState = null;
		}
	}
	
	public static function setMain (main:Sprite):Void
	{
		_manager._main = main;
	}
	
	public static function add (gamestate:IGameState):Void
	{
		_manager._queue.push (gamestate);
	}
}